#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include "led.h"

char str[] = "/sys/class/gpio/";

int openIO(int io)
{
	int pf,ret;
	char stmp[200];
	memset(stmp, 0, sizeof(stmp));
	sprintf(stmp,"%sgpio%d",str,io);
	ret=access(stmp,F_OK);    // /sys/class/gpio/gpioxxx is ok?
	if(ret == 0 )  //if file is ok
	{
		return 0;
	}
	// if gpioxxx is not ok
	sprintf(stmp,"%sexport",str);
	pf = open(stmp,O_WRONLY );     //open file
	if(pf == -1)
	{
		printf("Open file error.\n");
	}
	sprintf(stmp,"%d",io);
	write(pf,stmp,strlen(stmp));
	close(pf);
	return 0;
}
int closeIO(int io)
{
	int pf,ret;
	char stmp[200];
	memset(stmp, 0, sizeof(stmp));
	sprintf(stmp,"%sgpio%d",str,io);
	ret=access(stmp,F_OK);    // /sys/class/gpio/gpioxxx is ok?
	if(ret == -1 )  //if file is not
	{
		return 0;
	}
	// if gpioxxx is not ok
	sprintf(stmp,"%sunexport",str);
	pf = open(stmp,O_WRONLY );     //open file
	if(pf == -1)
	{
		printf("Open file error.\n");
	}
	sprintf(stmp,"%d",io);
	write(pf,stmp,strlen(stmp));
	close(pf);
	return 0;
	
}
int SetLed(int Led,int state)
{
	int pf,ret;
	char stmp[200];
	memset(stmp, 0, sizeof(stmp));
	
	openIO(Led);
	sprintf(stmp,"%sgpio%d/direction",str,Led);
	pf = open(stmp,O_WRONLY);
	write(pf,"out",3);
	close(pf);
	
	sprintf(stmp,"%sgpio%d/value",str,Led);
	pf = open(stmp,O_WRONLY);
	if(state == OFF)
	{
		write(pf,"1",1);
	}else if(state == ON)
	{
		write(pf,"0",1);
	}else{
		
	}
	close(pf);
	
	return 0;
}

